package com.jinzihan.web;

import com.jinzihan.entity.Classroom;
import com.jinzihan.entity.Page;
import com.jinzihan.service.ClassroomService;
import com.jinzihan.service.impl.ClassroomServiceImpl;
import com.jinzihan.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClassroomServlet extends BaseServlet{
    ClassroomService classroomService = new ClassroomServiceImpl();
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Classroom classroom = WebUtils.copyToClassroom(req);
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 0);
        pageNo += 1;
        classroomService.addClassroom(classroom);
        resp.sendRedirect(req.getContextPath()+"/manager/classroomServlet?action=page&pageNo="+pageNo);
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        classroomService.deleteClassroom(id);
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 0);
        resp.sendRedirect(req.getContextPath()+"/manager/classroomServlet?action=page&pageNo="+pageNo);
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        Classroom classroom = WebUtils.copyToClassroom(req);
        classroom.setId(id);
        classroomService.updateClassroom(classroom);
        resp.sendRedirect(req.getContextPath() + "/manager/classroomServlet?action=page&pageNo="+ req.getParameter("pageNo"));
    }

    protected void findClassroom(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        Classroom classroom = classroomService.queryClassroomById(id);
        req.setAttribute("classroom",classroom);
        req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
    }

    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数 pageNo 和 pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2 调用 ClassroomService.page(pageNo，pageSize)：Page 对象
        Page<Classroom> page = classroomService.page(pageNo,pageSize);
        page.setUrl("manager/classroomServlet?action=page");
        //3 保存 Page 对象到 Request 域中
        req.setAttribute("page",page);
        //4 请求转发到 pages/manager/book_manager.jsp 页面
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }
}
